import api from '../../api/api'
import * as types from '../mutation-types'

const state = {
  //用户登录状态
  loginStatus: JSON.parse(localStorage.getItem('loginStatus')) || false,
  // 用户登录信息
  userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
  // 存储 token
  token: JSON.parse(localStorage.getItem('token')) || '',
}

const actions = {
  //用户登录
  setUserInfo({ commit }, res) {
    localStorage.setItem('userInfo', JSON.stringify(res))
    localStorage.setItem('loginStatus', true)
    commit(types.SET_USER_INFO, res)
    commit(types.SET_LOGIN_STATUS, true)
  },

  // 退出登录
  setSignOut({ commit }) {
    localStorage.removeItem('loginStatus')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token');
    commit(types.SET_LOGIN_STATUS, false)
    commit(types.SET_USER_INFO, {})
  }

}

const getters = {
  loginStatus: state => state.loginStatus,
  userInfo: state => state.userInfo,
  token: state => state.token,
}

const mutations = {
  [types.SET_LOGIN_STATUS](state, status) {
    state.loginStatus = status
  },

  [types.SET_USER_INFO](state, res) {
    state.userInfo = res
  },

  // 存储token
  setToken (state, res) {
    state.token = res
    localStorage.setItem('token', JSON.stringify(res))
  },

}

export default {
  state,
  actions,
  getters,
  mutations
}
